<template>
	<gui-page ref="guiPage" :customHeader="true">
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" @clickLeftBack="clickLeftBack"
				:title="$t('hardwareOut.pageTitle')" :rightText="$t('distributedEnter.scanRecord')"
				@clickRight="clickRight"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="page-auto-noheight paddingbottom">
				<!-- 扫描条码 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('distributedEnter.barcodeScan') }}
					</view>
					<view class="custom-card-scan">
						<uni-easyinput class="uni-mt-5" suffixIcon="scan"
							:placeholder="$t('stockManage.pleaseScanCode')" v-model="data.scanValue" @confirm="confirm"
							@iconClick="iconClick">
						</uni-easyinput>
					</view>
				</view>
				<!-- 扫描条码 -->
				<view v-if="data.scanInfo" class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('distributedOut.atPresent') }}
					</view>
					<view class="custom-card-itemOne">
						<text
							class="item-info-title">{{ $t('distributedEnter.materialCode') }}：</text>{{ data.scanInfo.materialCode }}
					</view>
					<view class="custom-card-itemOne">
						<text
							class="item-info-title">{{ $t('distributedEnter.materialName') }}：</text>{{ data.scanInfo.materialName }}
					</view>
					<view class="custom-card-itemOne" v-if="data.scanInfo.materialSpec != ' '">
						<text
							class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{ data.scanInfo.materialSpec
								|| ''}}
					</view>
					<view class="custom-card-itemOne" v-if="data.scanInfo.unit">
						<text class="item-info-title">{{ $t('stockManage.materialUnit') }}：</text>{{ data.scanInfo.unit }}
					</view>
					<view class="custom-card-itemOne">
						<text
							class="item-info-title">{{ $t('pageTranslation.currentQtyMaterialCard') }}:</text>{{ data.scanInfo.currentQty }}
					</view>
					<view class="custom-card-itemOne">
						<text
							class="item-info-title">{{ $t('purchaseReturn.rejectedMaterialQty') }}：</text>{{ data.scanInfo.returnNum }}
					</view>
				</view>
				<view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
					<view class="gui-title-line"></view>
					<text class="gui-primary-text gui-h6"
						style="padding-left:50rpx; padding-right:50rpx;">{{ $t('purchaseReturn.generateInfo') }}</text>
					<view class="gui-title-line"></view>
				</view>
				<uni-card class="element-auto gui-margin-top card-my">
					<view class="element-auto" style="height: 300rpx">
						<zb-table :columns="data.column1" :stripe="true" :border="true" @customLook="customBtnFn"
							:cell-style="cellStyle" :cell-header-style="cellHeaderStyle" :data="data.wmsInstockDs">
						</zb-table>
					</view>
				</uni-card>
				<!-- 底部操作栏 -->
				<view class="page-bottom-box bottom-postion">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelCreatOrder">
						{{ $t('purchaseReturn.generateSheet') }}
					</view>
				</view>
			</view>
			<!-- 页面弹窗 -->
			<uni-popup ref="inputDialog" type="center">
				<view v-if="data.scanInfo" class="input-dialog-box">
					<view class="input-dialog-content">
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialCode') }}:{{ data.scanInfo.materialCode }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.materialName') }}:{{ data.scanInfo.materialName }}
						</view>
						<view class="input-dialog-item" v-if="data.scanInfo.materialSpec != ' '">
							{{ $t('distributedEnter.materialSpec') }}:{{ data.scanInfo.materialSpec || '' }}
						</view>
						<view class="input-dialog-item">
							{{ $t('distributedEnter.uom') }}:{{ data.scanInfo.unit }}
						</view>
						<view class="input-dialog-item">
							{{ $t('pageTranslation.currentQtyMaterialCard') }}:{{ data.scanInfo.currentQty -
								data.scanInfo.returnNum}}
						</view>
						<view class="input-dialog-item flexclass">
							<view>{{ $t('purchaseReturn.rejectedMaterialQty') }}：</view>
							<view class="input-dialog-item-count">
								<input @input="input" class="input" v-model="data.scanInfo.returnNum" type="number"
									:placeholder="$t('pageTranslation.pleaseInputTheQty')" />
							</view>
						</view>
					</view>
					<view class="input-dialog-footer">
						<view class="input-dialog-button" @click="cancelFn">
							{{ $t('popup.cancel') }}
						</view>
						<view class="input-dialog-button dialog-button-left" @click="scanConfirmFn">
							{{ $t('popup.confirm') }}
						</view>
					</view>
				</view>
			</uni-popup>

			<!-- 表格查看界面 -->
			<uni-popup ref="popup" type="center">
				<view v-if="data.wmsInstockDsInfo" class="input-dialog-box"
					style="padding: 40rpx 20rpx 20rpx 20rpx;border-radius: 22rpx;width: 600rpx;">
					<uni-icons class="popup-close-icons" type="closeempty" color="#9C9C9C" size="26"
						@click="closePopup"></uni-icons>
					<view class="custom-card-itemOne">
						<text
							class="item-info-title">{{ $t('distributedEnter.materialCode') }}：</text>{{ data.wmsInstockDsInfo.materialCode }}
					</view>
					<view class="custom-card-itemOne">
						<text
							class="item-info-title">{{ $t('distributedEnter.materialName') }}：</text>{{ data.wmsInstockDsInfo.materialName }}
					</view>
					<view class="custom-card-itemOne">
						<text
							class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{ data.wmsInstockDsInfo.materialSpec }}
					</view>
					<view class="custom-card-itemOne">
						<text
							class="item-info-title">{{ $t('hardware.receiptsQty') }}：</text>{{ data.wmsInstockDsInfo.qty }}
					</view>
					<view class="custom-card-itemOne">
						<text
							class="item-info-title">{{ $t('pageTranslation.retiredNumber') }}：</text>{{ data.wmsInstockDsInfo.returnTotalQty }}
					</view>
					<view class="custom-card-itemOne">
						<text
							class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{ data.wmsInstockDsInfo.unit }}
					</view>
					<view class="custom-card-itemOne">
						<text
							class="item-info-title">{{ $t('purchaseReturn.rejectedMaterialQty') }}：</text>{{ data.wmsInstockDsInfo.returnNum }}
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>

<script setup>
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import tableColor from '@/hooks/tableColor.js';
import { sortClass } from '@/utils/index.js'
import pdaScan from '@/hooks/pdaScan.js'
import graceJS from "@/Grace6/js/grace.js";
import { useStore } from "vuex";
import { ref, reactive, onMounted, computed, watch, toRaw } from 'vue';
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT, OPERATION_LOOK, OPERATION_SCAN } from '@/constant/index.js'
import { wmsInStockInfoById, selectRawPurReturnBarcode, commitRefund } from '@/api/api.js'
import { onBackPress } from '@dcloudio/uni-app';
import { toFixed4 } from '@/utils/index.js';
//JS国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

let { tableData } = tableColor();
const { cellStyle, cellHeaderStyle } = tableColor();
let popup = ref(null)
const { scan } = pdaScan()
// 接受来自父组件的传参 页面传值
const props = defineProps({
	poCode: String,
	voCode: String,
	returnTypeId: String,
});
let store = useStore();
let inputDialog = ref(null);

let data = reactive({
	stockList: [],//历史扫描数据
	scanValue: '',//当前扫描条码
	wmsReceiptDsInfo: undefined,// 查看当前信息
	scanInfo: undefined,//当前扫描条码
	id:'',
	poCode: props.poCode == 'null' ? '' : props.poCode, // 上级界面传过来
	voCode: props.voCode == 'null' ? '' : props.voCode,// 上级界面传过来的
	returnTypeId: props.returnTypeId == 'null' ? '' : props.returnTypeId,// 上级界面传过来的
	wmsInStockInfo: undefined,// 相应
	wmsInstockDs: [],// 入库单信息
	wmsInstockDsInfo: undefined,// 查看对应数据
	inputValue: '',
	column1: [{
		name: 'age',
		type: 'ailibtn',
		label: t('translationImage.operation'),
		scanValue: '',
		fixed: true,
		width: 95,
	},
	{
		name: 'materialCode',
		label: t('distributedEnter.materialCode'),
		width: 105,
		emptyString: '--'
	},
	{
		name: 'materialName',
		label: t('distributedEnter.materialName'),
	},

	{
		name: 'materialSpec',
		label: t('distributedEnter.materialSpec')
	},
	{
		name: 'qty',
		label: t('hardware.receiptsQty')
	},
	{
		name: 'unit',
		label: t('distributedEnter.uom')
	},
	{
		name: 'returnTotalQty',
		label: t('pageTranslation.retiredNumber'),
	}, {
		name: 'returnNum',
		width: 115,
		label: t('purchaseReturn.rejectedMaterialQty'),
	}
	],
	list: [],
})

onMounted(() => {
	console.log('开始监听PDA扫码')
	uni.$on('scancodedate', (data) => {
		console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
	getRequestData()
})

const input = (val) => {
	console.log(val)
	const num = val.detail.value
	if (Number(num) > data.scanInfo.currentQty) {
		uni.showToast({ title: t('pageTranslation.theInputQuantity'), icon: "none" });
		data.scanInfo.returnNum = toFixed4(data.scanInfo.currentQty)
		return
	}
}

// 查询初始化数据
const getRequestData = () => {
	let parmes = {
		poCode: data.poCode,
		voCode: data.voCode,
		returnType:data.returnTypeId,
		current: 1,
		size: 10,
		isSp: 'Y',
	}
	wmsInStockInfoById(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '五金仓采购退料'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_LOOK,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.code == 0) {
			data.wmsInStockInfo = res.data
			data.wmsInstockDs = res.data
			watcShowscanList() // 去手动调取计算监属性
		}
	})
}

// 剥离计算方法 用于方便调用
const watcShowscanList = () => {
	// 当前无本地记录扫码数据 但有历史记录手动赋值本地扫码信息
	if (!data.scanInfo && data.stockList.length > 0) {
		data.scanInfo = data.stockList[0]
	}
	// 当前有本地记录扫码数据 但无历史记录手动置空本地扫码信息
	if (data.scanInfo && data.stockList.length == 0) {
		data.scanInfo = undefined
	}
	// 遍历数组 查询当前扫描的物料信息 与当前的收集单信息相比对进行重新赋值
	data.wmsInstockDs.forEach(element => {
		let returnNum = 0
		data.stockList.forEach(item => {
			// 根据当前扫描的materialCode物料code  查询到相对应收集单信息
			if (element.materialCode == item.materialCode) {
				returnNum = returnNum + Number(item.returnNum)
			}
		});
		element.returnNum = toFixed4(returnNum) //物料数量
	});
}

data.stockList = computed(() => {
	return store.state.hardWare.stockList
})
//把扫描条码变为物料集合的二维数组
watch(() => data.stockList, (newVal) => {
	watcShowscanList()
}, {
	immediate: true,
	deep: true
});

// 用户调起相机扫码
const iconClick = async (type) => {
	console.log(type)
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}
// 用户点击键盘上搜索
const confirm = () => {
	getCode(data.scanValue, 'keydown')
}
// 获取code
const getCode = (code, type) => {
	let arr = data.stockList.filter(x => x.barcode == code)
	if (arr.length > 0) {
		uni.showToast({ title: t('JsInternational.repeatTo'), icon: "none" });
		return
	}
	data.scanValue = code
	let parmes = {
		barcode: code,
		selectType: 'purchaseReturn',
		inStockId: data.id,
		isSp: 'Y',
	}
	selectRawPurReturnBarcode(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '五金仓采购退料'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		// console.log(res)
		if (res.code == 0) {
			let bool = data.wmsInstockDs.some((item) => {
				return item.materialCode == res.data.materialCode
			})
			if (!bool) {
				uni.showToast({ title: t('materials.materialIsNot'), icon: "none" });
				return
			}
			data.scanInfo = res.data
			data.scanInfo.returnNum = null //
			// 筛选出和当前扫码一直的物料并提位
			if (data.wmsInstockDs.length && data.wmsInstockDs.length != 1) {
				for (var i = 0; i < data.wmsInstockDs.length; i++) {
					var item = {}
					if (data.wmsInstockDs[i].materialCode === res.data.materialCode) {
						item = data.wmsInstockDs[i]
						data.wmsInstockDs.splice(i, 1);
						data.wmsInstockDs.unshift(item)
						break;
					}
				}
			}
			inputDialog.value.open()
		} else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})
}
const scanConfirmFn = () => {
	// 退料数量：
	if (data.scanInfo.returnNum == null) {
		uni.showToast({ title: t('pageTranslation.pleaseInputTheQty'), icon: "none" });
		return;
	}
	if (Number(data.scanInfo.returnNum) == 0) {
		uni.showToast({ title: t('pageTranslation.qtyReturnedMaterial'), icon: "none" });
		return;
	}
	let wmsqty = 0
	let text = ''
	let scanInfo = data.scanInfo
	// 计算当前物料剩余的扫描容量
	data.wmsInstockDs.forEach((item) => {
		if (item.materialCode == scanInfo.materialCode) {
			let returnNum = item.returnNum ? Number(item.returnNum) : 0
			// wmsqty = Number(item.qty) - returnNum - Number(item.returnTotalQty)
			wmsqty = Number(item.qty) - returnNum
			text = item.materialName
		}
	})
	if (wmsqty - Number(scanInfo.returnNum) < 0) {
		uni.showToast({ title: t('JsInternational.Scanning') + `${text}` + t('JsInternational.qtyGreaterThan'), icon: "none" });
		return
	}
	store.dispatch('hardWare/setStockList', data.scanInfo)
	inputDialog.value.close();
}
// 查看
const customBtnFn = (item, index) => {
	data.wmsInstockDsInfo = item
	try {
		let inputParameter = JSON.stringify(item)
		let returnParameter = '无'
		let operationPicture = '五金仓采购退料'
		let callInterface = '无'
		let opertionParmes = {
			inputParameter,
			returnParameter,
			operationPicture,
			callInterface,
			responseCode: '无',//返回状态
			errorMessage: '无',//错误信息
			isPass: 'Y',//是否成功 Y N
			operationType: OPERATION_LOOK,
			module: 'WMS',
			source: "PDA",
		}
		basPdaOperationLogFn(opertionParmes)
	} catch (error) {
	}
	popup.value.open()
}
const closePopup = () => {
	popup.value.close()
}
const cancelFn = () => {
	inputDialog.value.close()
	data.scanInfo = undefined
	popup.value.close()
}
//弹框的确定按钮
const confirmFn = () => {
	inputDialog.value.close();
}

// 生成退料单
const handelCreatOrder = () => {
	if (data.stockList.length == 0) {
		uni.showToast({ title: t('stockManage.pleaseScanCode'), icon: "none" });
		return
	}
	let tepData = toRaw(data.stockList)
	let list = sortClass(tepData)
	let receiptBarcodes = []
	list.forEach(x => {
		x.forEach(k => {
			let item = {
				materialCode: '',//物料code
			}
			item.materialCode = k.materialCode
			item.barcode = k.barcode//条码barcode
			item.barcodeId = k.id//条码id
			item.warehouseCode = k.warehouseCode
			item.locationCode = k.locationCode
			// 传递表格行里面的行号
			item.line = data.wmsInstockDs.length == 1 ? data.wmsInstockDs[0].line : data.wmsInstockDs.forEach(a => {
				if (a.materialCode == k.materialCode) {
					return item.line
				}
			})
			item.instockDId = data.wmsInstockDs.length == 1 ? data.wmsInstockDs[0].id : data.wmsInstockDs.forEach(item => {
				if (item.barcode == k.materialCode) {
					return item.id
				}

			})
			item.qty = Number(k.returnNum)//用户输入的qty
			receiptBarcodes.push(item)
		})
	});
	let parmas = {
		isSp: 'Y',
		instockId: data.id, // 收料单id
		poCode: data.poCode,
		voCode:  data.voCode,
		instockCode: data.wmsInStockInfo.instockCode, //收料单code
		purReturnBarcodesItems: receiptBarcodes // 条码信息
	}
	console.log(parmas)
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	commitRefund(parmas).then(res => {
		console.log(res)
		try {
			let inputParameter = JSON.stringify(parmas)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '五金仓采购退料'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.code == 0) {
			//隐藏加载框
			uni.hideLoading();
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: "none" });
			//删除已提交的数据
			store.dispatch('hardWare/resetStockList')
			// navigateBack()
			// 返还上一个页面
			uni.navigateBack();
		} else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})

}

onBackPress((options) => {
	if (options.from == 'backbutton') {
		navBackCheck()
		return true;
	}
})
//导航栏左侧返回
const clickLeftBack = () => {
	navBackCheck()
}
const navBackCheck = () => {
	if (!data.stockList.length) {
		uni.navigateBack({
			delta: 1
		});
		return true
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.dispatch('hardWare/resetStockList')
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}
const clickRight = () => {
	navigate({
		url: '/pages/hardware/hardwareOutRecord'
	})
}
</script>

<style scoped lang="scss">
.input {
	font-size: 28rpx;
}
</style>
